<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se tem permissao
validaPermissao(2);

// Verifica se tem permissao
if (!$_GET['id'])
{
	forbidden();
}

//Descobre algo sobre o report
$report = query_fetch("SELECT * FROM reports WHERE id='{$_GET['id']}' LIMIT 1");

// Se nao existe, cai fora
if (!$report)
{
    response_404();
}

// Se a permissao do usuario eh inferior a de administrador e o report ja foi aceito ou foi criado por outro manager
if (nivelAutenticado() <= 2 && $report['accepted'])
{
	forbidden();
}
else if (nivelAutenticado() == 2 && !$report['accepted'])
{
	$is_manager = query_fetch("SELECT report_id FROM clocks WHERE report_id={$report['id']} AND " .
	"employee_id={$_SESSION[site_id]['id']} AND clocks.manager = TRUE");
	if (!$is_manager['report_id'])
	{
		forbidden();
	}
}

$report_state_was = $report['state'];

// Verifica acao aceitar
if (isset($_GET['accept']) && $report['state'] == REVIEW)
{
	query_bd("UPDATE reports SET state=" . ACCEPTED . " WHERE id={$report['id']} LIMIT 1");
	$report['state'] = ACCEPTED;

	if (isset($_GET['income']))
	{
		query_bd("INSERT INTO duedates VALUES " .
		"(NULL, 'unnamed', '" . $PERIOD[$report['period']] . " at " .
		date("l, F d Y", strtotime($report['reportdate'])) . "', " . REPORT . ", '" .
		date("Y-m-d", strtotime($report['reportdate'])) .
		"' , 0.00, FALSE, " . REPORT . ", {$report['id']}, NULL, " .
		($report['obs']? "'" . mysql_real_escape_string($report['obs']) . "')" : "NULL)"));
	}

	$_GET['msg'] = "This Shift Report was reviewed and accepted into the system.";
}
// Verifica acao deletar
else if (isset($_GET['delete']) && $report['state'] == REVIEW)
{
//	query_bd("UPDATE reports SET state=" . TRASH ." WHERE id={$report['id']}");
//	$report['state'] = TRASH;
	query_bd("DELETE FROM reports WHERE id={$report['id']} LIMIT 1");
	query_bd("DELETE FROM cars_paid WHERE report_id={$report['id']}");
	query_bd("DELETE FROM clocks WHERE report_id={$report['id']}");
	query_bd("DELETE FROM startings_endings WHERE report_id={$report['id']}");
//	query_bd("DELETE FROM duedates WHERE references_to = " . REPORT . " AND reference_id={$report['id']}");
//	query_bd("DELETE FROM period_duedates WHERE references_to = " . REPORT . " AND reference_id={$report['id']}");
	header( "Location: reports.php?msg=The previous reviewed Shift Report was excluded" );
	die();
}
// Verifica acao unaceitar
else if (isset($_GET['unaccept']) && $report['state'] == ACCEPTED)
{
	query_bd("UPDATE reports SET state=" . REVIEW . " WHERE id={$report['id']}");
	$report['state'] = REVIEW;
	$_GET['msg'] = "This Shift Report was sent back for review.";
}

// Verifica se ha income associado ao report
$income = query_fetch("SELECT * FROM duedates WHERE references_to=". REPORT ." AND reference_id={$report['id']}");

// Turn on output buffering
ob_start();

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Shift Report');
pagina_head();

?>
<script type='text/javascript' language='JavaScript'>

function confirmGenerateDuedate()
{
	if (confirm("Do you really want to accept this report?"))
	{
		if (confirm("Do you want to register an income regarding this report?"))
		{
			document.getElementById("accept_link").href += "&income=1";
		}
		return true;
	}
	return false;
}

function confirmExcludeIncome()
{
	if (confirm("Do you really want to exclude this report?"))
	{
		if (confirm("Do you want to exclude the income regarding this report as well?"))
		{
			document.getElementById("exclude_link").href += "&exclude_income=1";
		}
		return true;
	}
	return false;
}

</script>
<?php

// Mostra opcoes
echo "<ul id=opcoes>";
// Se o report ainda nao foi aceito
if ($report['state'] == REVIEW)
{
	if (nivelAutenticado() >= 3)
	{
		echo "<li><a href='report_edit.php?id={$report['id']}'><img src='img/edit.png' alt=''>Edit report</a></li>";
		echo "<li class='positive'><a href='report.php?id={$report['id']}&amp;accept=1' id=accept_link ",
		($income? "" : "onClick='return confirmGenerateDuedate()'"), " ><img src='img/ok.png' alt=''>Accept report</a></li>";
	}
	echo "<li class='negative'><a href='report.php?id={$report['id']}&amp;delete=1' id=exclude_link ",
	($income? "onClick='return confirmExcludeIncome()'" : "onClick='return confirm(\"Do you really want to exclude this report?\");'"),
	" ><img src='img/cancel.png'/>Exclude report</a></li>";
}
else if ($report['state'] == ACCEPTED)
{
	if (nivelAutenticado() >= 3)
		echo "<li class='negative'><a href='report.php?id={$report['id']}&amp;unaccept=1' ",
		"onClick='return confirm(\"Do you really want to send this report back for review?\");' >",
		"<img src='img/cancel.png' alt=''>Send report back for review</a></li>";
}
if ($income)
	echo "<li><a href='income.php?id={$income['id']}'><img src='img/payday.png' alt=''>Income</a></li>";
echo "<li><a href='report.php?id={$report['id']}&amp;print=1' target='_blank'>",
	"<img src='img/print.png' alt=''>Print</a></li>";
echo "</ul><br>";

// Mostra dados do report
echo "<div class=dados_estaticos>";
echo "<h1>Shift Report</h1><br>";
echo "<dl>";
if ($report['modified'] > 0)
	echo "<dt>Modified</dt><dd>", date("l, F d Y, H:i", strtotime($report['modified'])), "</dd>";

echo "<dt>Date</dt><dd>", date("l, F d Y", strtotime($report['reportdate'])), "</dd>";

// Busca nome da locacao ou evento
if ($report['special_event'])
{
	$evento = query_fetch("SELECT name, contact_id, customer_id FROM events WHERE id={$report['location_event_id']} LIMIT 1");
	$event_contact = query_fetch("SELECT * from contacts WHERE id={$evento['contact_id']} LIMIT 1");
	$customer = query_fetch("SELECT contacts.name FROM contacts, customers WHERE " .
		"customers.id={$evento['customer_id']} AND contacts.id=customers.contact_id LIMIT 1");

	echo "<dt>Special Event</dt><dd>{$evento['name']}</dd>";
	echo "<dt>Event customer</dt><dd><a href='customer.php?id={$evento['customer_id']}'>{$customer['name']}</a></dd>";
	echo "<dt>Event contact</dt><dd><address>",
		"{$event_contact['number']} {$event_contact['street']} {$event_contact['complement']}, ",
		"{$event_contact['city']} {$event_contact['state']}, {$event_contact['zipcode']} ",
		"{$event_contact['phone']} {$event_contact['cellphone']} {$event_contact['email']}</address></dd>";

	$reportname = $evento['name'];
}
else
{
	$locacao = query_fetch("SELECT contacts.name FROM locations, contacts" .
		" WHERE locations.id={$report['location_event_id']} AND contacts.id = locations.locationcontact LIMIT 1");

	echo "<dt>Location</dt><dd><a href='location.php?id={$report['location_event_id']}'>{$locacao['name']}</a></dd>";

	$reportname = $locacao['name'];
}

//Periodo
echo "<dt>Period</dt><dd>{$PERIOD[$report['period']]}</dd>";

//payrates e tax
echo "<dt>Manager payrate</dt><dd>", show_money($report['manager_payrate']), "</dd>";
echo "<dt>Valet payrate</dt><dd>", show_money($report['valet_payrate']), "</dd>";
if ($report['insurance_tax'] > 0)
	echo "<dt>Insurance tax</dt><dd>", show_money($report['insurance_tax']), " per car</dd>";
if ($report['tip_percent']>0)
	echo "<dt>Tip percent</dt><dd>", ($report['tip_percent']*100.0), "% </dd>";

echo "</dl>";
echo "<hr><h2>Time Card and Labor</h2><br>";
echo "<dl>";
// Calcula total de labor do report
$clocks_result = query_bd("SELECT * FROM clocks WHERE report_id={$report['id']} ORDER BY manager DESC");

// Escreve time card
echo "<dd><ul class='dados_estaticos'>";
while ($clock = mysql_fetch_array($clocks_result))
{
	// Escreve dados
	$employee_name = query_fetch("SELECT contacts.name FROM contacts, employees " .
	"WHERE contacts.id=employees.contact_id AND employees.id={$clock['employee_id']} LIMIT 1");

	echo "<li><a href='employee.php?id={$clock['employee_id']}'>{$employee_name['name']}</a>",
	($clock['manager']? "(manager)" : ""),
	" <strong>in:</strong> ", formatTime($clock['intime']), "</dd>" ,
	" <strong>out:</strong> ", formatTime($clock['outtime']), "</dd>" ,
	" <strong>labor:</strong> ", formatTime($clock['labor']), "</dd>" ,
	" <strong>labor expense(+tip):</strong> ", show_money(-$clock['labor_expense']), "</dd>",
    "</li>";
}
echo "</ul></dd>";

echo "<dt>Total labor</dt><dd>", formatTime($report['labor']), "</dd>";
echo "<dt>Total labor expense</dt><dd>", show_money(-$report['labor_expense']), "</dd>";

echo "</dl>";
echo "<hr><h2>Cars information</h2><br>";
echo "<dl>";

// Void, validated, hosted, paid
echo "<dt>Cars void</dt><dd>", ($report['cars_void']? $report['cars_void'] : "-"), "</dd>";
echo "<dt>Cars validated</dt><dd>", ($report['cars_validated']? $report['cars_validated'] : "-"), "</dd>";
echo "<dt>Cars hosted</dt><dd>", ($report['cars_hosted']? $report['cars_hosted'] : "-"), "</dd>";

$paid_result = query_bd("SELECT cars, charge FROM cars_paid WHERE report_id={$report['id']}");

$total_cars_paid = 0;
$cars_paid_income = 0.0;
echo "<dd><ul class='dados_estaticos'>";
while ($cars_paid = mysql_fetch_array($paid_result))
{
	echo "<li>{$cars_paid['cars']} at ", show_money($cars_paid['charge']),
	" = ", show_money($cars_paid['cars']*$cars_paid['charge']), "</li>";
	$total_cars_paid += $cars_paid['cars'];
	$cars_paid_income += $cars_paid['cars'] * $cars_paid['charge'];
}
echo "</ul></dd>";

echo "<dt>Charged cars</dt><dd>", ($total_cars_paid? $total_cars_paid : "-"), "</dd>";

$startings_endings = query_bd("SELECT start, ending, start_used FROM startings_endings WHERE report_id={$report['id']}");

echo "<dd><dl class='dados_estaticos'>";
while ($starting_ending = mysql_fetch_array($startings_endings))
{
	echo "<dt>Starting/Ending</dt><dd>", sprintf("%06d", $starting_ending['start']),
	" / ", sprintf("%06d", $starting_ending['ending']),
	" = ", ($starting_ending['ending']-$starting_ending['start']), " tickets used",
	($starting_ending['start_used']? "<small>(starting ticket used)</small>" : ""),
	"</dd>";
}
echo "</dl></dd>";

// Cars
$cars = $report['cars_void'] + $report['cars_validated'] + $report['cars_hosted'] + $total_cars_paid;
echo "<dt>Total cars</dt><dd>", ($cars? $cars : "-"), "</dd>";

// Charge income, tip income, insurance income
$insurance_income = $cars * $report['insurance_tax'];
$tip_income = ($report['tip']-$insurance_income);
$tip_income = max(0, $tip_income);

echo "</dl>";
echo "<hr><h2>Incomes</h2><br>";
echo "<dl>";

echo "<dt>Charge income</dt><dd>", show_money($cars_paid_income), "</dd>";
if ($insurance_income > 0)
	echo "<dt>Insurance income</dt><dd>", show_money($insurance_income), "</dd>";

// Total income
$total_income = $cars_paid_income + $tip_income;

if ($tip_income > 0)
{
	echo "<dt>Tip income</dt><dd>", show_money($tip_income), "</dd>";
	echo "<dt>Total income</dt><dd>", show_money($total_income), "</dd>";
}

echo "<dd><hr></dd>";

// Balance
$balance = $cars_paid_income - $report['labor_expense'];
echo "<dt>Balance: </dt><dd>", show_money($balance), "</dd>";

// Expense car
$income_car = ($cars>0? $total_income/$cars : 0);
$expense_car = ($cars>0? $report['labor_expense']/$cars : 0);

echo "<dt>Income per car</dt><dd>", show_money($income_car), "</dd>";
echo "<dt>Expense per car</dt><dd>", show_money(-$expense_car), "</dd>";
echo "<dt>Balance per car</dt><dd>", show_money($income_car-$expense_car), "</dd>";

if ($report['obs'])
	echo "<hr><dt>Observations</dt><dd>{$report['obs']}</dd>";

echo "</dl>";
echo "</div>";

//Verifica se ira criar um income para o report
if (isset($_GET['accept']) && $report_state_was == REVIEW && isset($_GET['income']))
{
	if ($total_income > 0)
		query_bd("UPDATE duedates SET name='" . sanitizeSQL($reportname) . "', value={$total_income} WHERE id={$income['id']} LIMIT 1");
	else
	{
		query_bd("DELETE FROM duedates WHERE id={$income['id']} LIMIT 1");

		ob_end_clean();
		header("Location: report.php?id={$_GET['id']}&msg=Warning: No income was generated because there is nothing to receive");
		die();
	}
}

// Finaliza pagina
pagina_fim();
ob_end_flush();
?>
